<template>
  <div class="app-container">
    <!-- 高级查询 -->
    <el-form v-show="searchVisible" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="活动名称:">
        <el-input v-model="queryParams.activityName" size="small" placeholder="请输入活动名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermission="['marketing:couponActivity:insert']" type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermission="['marketing:couponActivity:update']" type="success" icon="el-icon-edit" size="mini" :disabled="isSingle" @click="handleEdit">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermission="['marketing:couponActivity:delete']" type="danger" icon="el-icon-delete" size="mini" :disabled="isMultiple" @click="handleRemove">删除</el-button>
      </el-col>
      <right-toolbar :show-search.sync="searchVisible" @queryTable="handleQuery" />
    </el-row>

    <!-- 数据列表 -->
    <el-table v-loading="loading" :data="page.records" highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动编码" align="center" prop="activityCode" />
      <el-table-column label="活动名称" align="center" prop="activityName" />
     <el-table-column label="活动类型" align="center" prop="activityType" />
        <!-- <template slot-scope="scope">
          <span>{{ activityTypeFormat(scope.row.activityType) }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="活动开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
     <!-- <el-table-column label="金额" align="center" prop="amount" />
      <el-table-column label="发行总量" align="center" prop="publishQty" />
      <el-table-column label="已领取数量" align="center" prop="receivedQty" />
      <el-table-column label="已使用数量" align="center" prop="usedQty" />
      <el-table-column label="每人限领" align="center" prop="limitQty" />
      <el-table-column label="使用类型" align="center" width="180">
        <template slot-scope="scope">
          <span>{{ useTypeFormat(scope.row.useType) }}</span>
        </template>
      </el-table-column> -->
     <!-- <el-table-column label="使用门槛" align="center" prop="useCondition" /> -->
      <el-table-column label="活动状态" align="center" prop="status" />
      <el-table-column label="说明" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-hasPermission="['marketing:couponActivity:update']" size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
          <el-button v-hasPermission="['marketing:couponActivity:update']" size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">修改</el-button>
          <el-button v-hasPermission="['marketing:couponActivity:delete']" size="mini" type="text" icon="el-icon-delete" @click="handleRemove(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="page.total>0" :total="page.total" :page.sync="page.current" :limit.sync="page.pageSize" @pagination="handleQuery" />

    <!-- 添加/修改对话框 -->
    <el-dialog :title="couponActivityFormDialog.title" :visible.sync="couponActivityFormDialog.visible" :close-on-click-modal="false" :before-close="resetCouponActivityFormDialog" width="500px" append-to-body>
      <el-form ref="couponActivityForm" :model="couponActivityFormData" :rules="couponActivityFormRules" label-width="100px">
        <el-form-item label="活动编码" prop="activityCode">
          <el-input v-model="couponActivityFormData.activityCode" placeholder="请输入活动编码" />
        </el-form-item>
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="couponActivityFormData.activityName" placeholder="请输入活动名称" />
        </el-form-item>
       <el-form-item label="活动类型" prop="activityType">
          <el-select v-model="couponActivityFormData.activityType" style="width: 100%" placeholder="请选择活动类型">
          <!--  <el-option v-for="option in options.activityTypeOptions" :key="option.dictValueCode" :label="option.dictValueName" :value="option.dictValueCode" />
          -->  <el-option v-for="option in options.actOptions" :key="option.key" :label="option.label" :value="option.label" />
         </el-select>
        </el-form-item>
        <el-form-item label="活动开始时间" prop="startTime">
          <el-date-picker v-model="couponActivityFormData.startTime" type="date" value-format="yyyy-MM-dd" size="small" style="width: 100%" placeholder="选择活动开始时间" clearable />
        </el-form-item>
        <el-form-item label="活动结束时间" prop="endTime">
          <el-date-picker v-model="couponActivityFormData.endTime" type="date" value-format="yyyy-MM-dd" size="small" style="width: 100%" placeholder="选择活动结束时间" clearable />
        </el-form-item>
      <!--  <el-form-item label="面值" prop="amount">
          <el-input v-model.number="couponActivityFormData.amount" placeholder="面值只能是数值，限2位小数" class="input-width">
            <template slot="append">元</template>
          </el-input>
        </el-form-item> -->
        <!-- <el-form-item label="发行总量" prop="publishQty">
          <el-input v-model="couponActivityFormData.publishQty" placeholder="只能输入正整数" class="input-width">
            <template slot="append">张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="每人限领" prop="limitQty">
          <el-input v-model="couponActivityFormData.limitQty" placeholder="只能输入正整数" class="input-width">
            <template slot="append">张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="使用门槛" prop="useCondition">
          <el-input v-model.number="couponActivityFormData.useCondition" placeholder="只能输入正整数" class="input-width">
            <template slot="prepend">满</template>
            <template slot="append">元可用</template>
          </el-input>
        </el-form-item>
        <el-form-item label="使用类型" prop="useType">
          <el-radio-group v-model="couponActivityFormData.useType">
            <el-radio-button v-for="option in options.useTypeOptions" :key="option.dictValueCode" :label="option.dictValueCode">{{ option.dictValueName }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="couponActivityFormData.useType === `goods`">
          <el-select v-model="selectedGoodsId" :remote-method="handleGoodsQuery" :loading="selectGoodsLoading" filterable remote reserve-keyword clearable placeholder="商品名称/商品货号">
            <el-option v-for="goods in options.goodsOptions" :key="goods.goodsId" :label="goods.goodsName" :value="goods.goodsId">
              <span style="float: left">{{ goods.goodsName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">NO.{{ goods.sn }}</span>
            </el-option>
          </el-select>
          <el-button @click="handleAddGoodsRel()">添加</el-button>
          <el-table ref="productRelationTable" :data="couponActivityFormData.couponGoodsRelList" tyle="width: 100%;margin-top: 20px" border>
            <el-table-column label="商品名称" align="center">
              <template slot-scope="scope">{{ scope.row.goodsName }}</template>
            </el-table-column>
            <el-table-column label="货号" align="center" width="120">
              <template slot-scope="scope">NO.{{ scope.row.sn }}</template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleRemoveGoodsRel(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item> -->
        <el-form-item label="说明" prop="remark">
          <el-input v-model="couponActivityFormData.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmCouponActivityFormDialog">确 定</el-button>
        <el-button @click="resetCouponActivityFormDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CouponActivityApi from '@/api/marketing/CouponActivityApi'
import SpuApi from '@/api/goods/SpuApi'
import DictValueApi from '@/api/system/DictValueApi'

const defaultCouponActivityFormData = {
  activityName: null,
  activityType: null,
  amount: null,
  publishQty: null,
  limitQty: null,
  useType: null,
  useCondition: null,
  startTime: null,
  endTime: null,
  storeId: null,
  status: '0',
  couponGoodsRelList: []
}
export default {
  name: 'CouponActivityList',
  data() {
    return {
      options: {
        // activityTypeOptions: [],
        actOptions: this.$constant.actTypeOptions,
        useTypeOptions: [],
        goodsOptions: []
      },
      queryParams: {
        activityName: null,
        isValid: this.$constant.Y
      },
      goodsQueryParams: {
        goodsName: null,
        isValid: this.$constant.Y
      },
      page: {
        current: 1,
        pageSize: 10,
        total: 0,
        records: []
      },
      couponActivityFormDialog: {
        title: '',
        visible: false
      },
      couponActivityFormData: Object.assign({}, defaultCouponActivityFormData),
      couponActivityFormRules: {
      },
      selectedGoodsId: null,
      loading: true,
      selectGoodsLoading: false,
      searchVisible: true,
      multipleSelection: [],
      isSingle: true,
      isMultiple: true
    }
  },
  created() {
    this.handleQuery()
    this.loadOptions()
  },
  methods: {
    loadOptions() {
      // DictValueApi.list({ dictCode: 'mms_coupon_activity_type' }).then(response => {
      //   this.options.activityTypeOptions = response.data
      // })
      DictValueApi.list({ dictCode: 'mms_coupon_use_type' }).then(response => {
        this.options.useTypeOptions = response.data
      })
    },
    handleAdd() {
      this.openCouponActivityFormDialog()
    },
    handleAddGoodsRel() {
      if (this.selectedGoodsId === null) {
        this.$message('请先选择商品')
        return
      }
      SpuApi.get(this.selectedGoodsId).then(response => {
        const couponGoodsRel = {
          spuId: response.data.id,
          goodsName: response.data.goodsName,
          sn: response.data.sn
        }
        this.couponActivityFormData.couponGoodsRelList.push(couponGoodsRel)
      })
    },
    handleRemove(row) {
      const ids = row.id || this.multipleSelection.map(item => item.id)
      this.$confirm('是否确认删除数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return CouponActivityApi.remove(ids)
      }).then(() => {
        this.handleQuery()
        this.$message.success('删除成功')
      })
    },
    handleRemoveGoodsRel(index, row) {
      this.couponActivityFormData.couponGoodsRelList.splice(index, 1)
    },
    handleEdit(row) {
      const id = row.id || this.multipleSelection.map(item => item.id)[0]
      this.openCouponActivityFormDialog(id)
    },
    handleView(row) {
      this.$router.push({
        path: `/couponActivity/couponList`,
        query: {
          activityId: row.id
        }
      })
    },
    handleQuery() {
      this.loading = true
      CouponActivityApi.page(this.queryParams, this.page).then(response => {
        this.page.records = response.data.records
        this.page.total = response.data.total
        this.loading = false
      }, () => {
        this.loading = false
      })
    },
    handleGoodsQuery(spuName) {
      SpuApi.list({ spuName: spuName.trim() }).then(response => {
        this.options.goodsOptions = response.data
      })
    },
    handleExport() {
      this.$confirm('是否确认导出数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return CouponActivityApi.exportData(this.queryParams)
      }).then(response => {
        this.$common.download(response.data)
      })
    },
    openCouponActivityFormDialog(id) {
      this.couponActivityFormDialog.visible = true
      if (id) {
        this.couponActivityFormDialog.title = '促销活动-修改'
        CouponActivityApi.get(id).then(response => {
          this.couponActivityFormData = {
            ...this.couponActivityFormData,
            ...response.data
          }
        })
      } else {
        this.couponActivityFormDialog.title = '促销活动-添加'
      }
    },
    confirmCouponActivityFormDialog() {
      this.$refs['couponActivityForm'].validate(valid => {
        if (valid) {
          if (this.couponActivityFormData.id) {
            CouponActivityApi.edit(this.couponActivityFormData).then(response => {
              this.$message.success('修改成功')
              this.resetCouponActivityFormDialog()
              this.handleQuery()
            })
          } else {
            CouponActivityApi.add(this.couponActivityFormData).then(response => {
              this.$message.success('添加成功')
              this.resetCouponActivityFormDialog()
              this.handleQuery()
            })
          }
        }
      })
    },
    resetCouponActivityFormDialog() {
      this.couponActivityFormDialog = {
        title: '',
        visible: false
      }
      this.couponActivityFormData = Object.assign({}, defaultCouponActivityFormData)
      this.resetForm('couponActivityForm')
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      this.isSingle = selection.length !== 1
      this.isMultiple = !selection.length
    },
    resetQuery() {
      this.page.current = 1
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // activityTypeFormat(activityType) {
    //   return this.$common.getDictValueName(this.options.activityTypeOptions, activityType)
    // },
    useTypeFormat(useType) {
      return this.$common.getDictValueName(this.options.useTypeOptions, useType)
    }
  }
}
</script>
